/* programme calculant fibo(x) avec la bibli pthread*/

#include <pthread.h> 
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void* fibonacci(void* i)
{
  unsigned int *value =i;
  unsigned int *value_1=malloc(sizeof(unsigned int));
  unsigned int *value_2=malloc(sizeof(unsigned int));

  if((*value)<=1){
    int* ret=malloc(sizeof(int));
    *ret=1;
    return ret;
  }
  else
    {
      unsigned int *result=malloc(sizeof(unsigned int));
      pthread_t thread1,thread2;
      *value_1=*value-1;
      *value_2=*value-2;  
      pthread_create(&thread1,NULL,&fibonacci,(void*)value_1);
      pthread_create(&thread2,NULL,&fibonacci,(void*)value_2);
      pthread_join(thread1,(void**)&value_1);
      pthread_join(thread2,(void**)&value_2); 
      *result= (*value_1)+(*value_2);
      free(value_1);
      free(value_2);
      return result;
    }
}


int main(int argv, char** argc)
{
  
  if(argv!=2){
    printf("mettre un entier positif en argument\n");
    return 0;
  }
  
  int *value=malloc(sizeof(int));
  *value=atoi(argc[1]);
  if(*value>30)
    {
      printf("votre valeur est trop importante\n mettre un entier <10 pour ne pas créer trop de thread\n");
      return EXIT_FAILURE;
    }
  if(*value<=1)
    {
      printf(" fibo(%d)= 1\n",*value);
      return EXIT_SUCCESS;
    }

  double debut, fin;
  debut=clock();
  pthread_t thread;
  int* result=malloc(sizeof(int));
  *value=*value-1;
  pthread_create(&thread,NULL, fibonacci,(void*)value);
  pthread_join(thread,(void**)&result);
  printf("le resultat : fibo(%d)=%d\n",(*value+1), *result);
  free(value);
  free(result);
  fin=clock();
  fprintf(stderr,"temps d'exécution : %f s\n",(double) (fin-debut)/(double)CLOCKS_PER_SEC);
  return EXIT_SUCCESS;
}
